// 保存截图
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>

#include "save_bmp.h"

#define RIGHT_MARGIN 100  // 右边框的宽度

// 保存屏幕截图为BMP文件
int save_screen_shot_as_bmp(int (*lcd_mmap)[WIDTH], const char *save_name, char *account)
{
    printf("%s\n", save_name);
    const int width = WIDTH- RIGHT_MARGIN; // 减去右边框的宽度
    const int height = HEIGHT;
    char user_dir[30] = {0};
    char file_name[30] = {0};

    sprintf(user_dir, "./res/user/%s/", account);
    mkdir(user_dir, 0777);

    sprintf(file_name, "%s%s.bmp", user_dir, save_name);

    FILE *fp = fopen(file_name, "wb");
    if (!fp)
    {
        perror("Cannot open file");
        return -1;
    }

    // 创建并写入BMP文件头
    BITMAPFILEHEADER bmpFileHeader;
    bmpFileHeader.bfType = 19778; // 'BM'
    bmpFileHeader.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + (width * height * 4);
    bmpFileHeader.bfReserved1 = 0;
    bmpFileHeader.bfReserved2 = 0;
    bmpFileHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
    fwrite(&bmpFileHeader, sizeof(BITMAPFILEHEADER), 1, fp);

    // 创建并写入BMP信息头
    BITMAPINFOHEADER bmpInfoHeader;
    bmpInfoHeader.biSize = sizeof(BITMAPINFOHEADER);
    bmpInfoHeader.biWidth = width;
    bmpInfoHeader.biHeight = height;
    bmpInfoHeader.biPlanes = 1;
    bmpInfoHeader.biBitCount = 24;
    bmpInfoHeader.biCompression = 0;
    bmpInfoHeader.biSizeImage = width * height * 3;
    bmpInfoHeader.biXPelsPerMeter = 0;
    bmpInfoHeader.biYPelsPerMeter = 0;
    bmpInfoHeader.biClrUsed = 0;
    bmpInfoHeader.biClrImportant = 0;
    fwrite(&bmpInfoHeader, sizeof(BITMAPINFOHEADER), 1, fp);

    // 再写入颜色数据
    // argb转成bgr，从图片底部开始写入数据 
    for (int y = height - 1; y >= 0; y--)
    {
        for (int x = 0; x < width; x++)
        {
            unsigned char b = lcd_mmap[y][x] & 0xff;
            unsigned char g = (lcd_mmap[y][x] & 0xff00) >> 8;
            unsigned char r = (lcd_mmap[y][x] & 0xff0000) >> 16;
            unsigned char pixelData[3] = {b, g, r};
            fwrite(&pixelData, sizeof(pixelData), 1, fp);
        }
    }
    fclose(fp);
    return 0;
}